package com.nhjf.admin.controller.finetTalk;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;
import com.nhjf.admin.common.util.SysProperties;
import com.nhjf.admin.util.Jurisdiction;
import com.nhjf.admin.util.PictureUtil;
import com.nhjf.common.page.Pagination;
import com.nhjf.model.finetTalk.FinetTalk;
import com.nhjf.model.system.Role;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.Teacher;
import com.nhjf.pojo.dto.finetTalk.FinetTalkDto;
import com.nhjf.pojo.dto.result.ServiceResultDto;
import com.nhjf.pojo.qo.finetTalk.FinetTalkQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.service.finetTalk.FinetTalkService;
import com.nhjf.service.system.AdminSessionService;
import com.nhjf.service.system.UserService;
import com.nhjf.service.teachers.TeachersService;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import net.sf.json.JSONObject;


@Controller
@RequestMapping("/finetTalk")
public class FinetTalkCountroller {

	@Autowired
	private FinetTalkService finettalkService;
	@Autowired
	private TeachersService teachersService;

	//精讲后台发布：添加
	@RequestMapping("/speak_addTz")
	public String addto(){
		return "/finetTalk/finetTalk_add.html";
	}
	//精讲：精讲列表
	@ResponseBody
	@RequestMapping("/speak_list")
	public String speak(@RequestParam(value = "page", defaultValue = "1")Integer page) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			Pagination pagination = new Pagination();
			pagination.setPageSize(10);
			pagination.setPageNo(page);
			FinetTalkQo finettalkQo=new FinetTalkQo();
			finettalkQo.setSeachfinetTalkid(true);
			pagination.setCondition(finettalkQo);
			pagination = finettalkService.queryPagination(pagination);
			resMap.put("code", "200");
			resMap.put("message", pagination);
			return JSONObject.fromObject(resMap).toString();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			resMap.put("code", "200");
			resMap.put("message","出现异常！");
		}
		resMap.put("code", "200");
		resMap.put("message","查询失败！");
		return JSONObject.fromObject(resMap).toString();

	}



	//精讲：精讲id查看
	@ResponseBody
	@RequestMapping("/speak_view")
	public String speakview(String speakid) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		FinetTalkDto finetTalkDto=new FinetTalkDto();
		try {

			FinetTalkQo finettalkQo=new FinetTalkQo();
			finettalkQo.setFinetTalkid(Long.parseLong(speakid));
			finettalkQo.setSeachfinetTalkid(true);
			FinetTalk finetTalk=finettalkService.queryUnique(finettalkQo);
			finetTalkDto.setTitle(finetTalk.getTitle());
			finetTalkDto.setReleasetime(finetTalk.getReleasetime());
			//			finetTalkDto.setPublisherId(finetTalk.getPublisher());
			finetTalkDto.setContent(finetTalk.getContent());
			finetTalkDto.setPageviews(finetTalk.getPageviews());
			resMap.put("code", "200");
			resMap.put("message",finetTalkDto);
			return JSONObject.fromObject(resMap).toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			resMap.put("code", "200");
			resMap.put("message","出现异常！");
		}

		resMap.put("code", "200");
		resMap.put("message","查看内容失败！");
		return JSONObject.fromObject(resMap).toString();
	}


	//精讲后台发布:添加
	@ResponseBody
	@RequestMapping("/speak_add")
	public String speakrelease(MultipartFile pic,HttpServletRequest request,HttpServletResponse response
			,FinetTalkQo qo) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
 			Set<Role> set= user.getRoleList();
			Iterator<Role> iter = set.iterator();
			Role roles=new Role();
			while(iter.hasNext()) {
				roles=iter.next();
				break;
			}
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}

			if (pic.isEmpty()) {
				resMap.put("code", "500");
				resMap.put("message", "上传图片不可为空");
				return JSONObject.fromObject(resMap).toString();
			}
			int returnTag = -1;
			SysProperties sysProperties=SysProperties.getInstance();

			String imgPath=sysProperties.get("toragesPath");
			//获取图片原始文件名
			String finetTalk = pic.getOriginalFilename();
			System.out.println(finetTalk);
			//文件名使用当前时间
			String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			// 获取上传图片的扩展名(jpg/png/...)
			String extension = FilenameUtils.getExtension(finetTalk);
			String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
			boolean flag = false;
			// 判断文件格式是否合法
			for (String str : regular) {
				if (extension.equalsIgnoreCase(str)) {
					flag = true;
				}
			}
			if (!flag) {
				returnTag = 0;
				resMap.put("code", "500");
				resMap.put("message", "上传图片格式不正确！");
				return JSONObject.fromObject(resMap).toString();
			}
			// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
			String path =imgPath+user.getId() +"/" +name + "." + extension;
			//图片上传的绝对路径

			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 上传图片
			pic.transferTo(new File(path));
			qo.setSeachfinetTalkid(true);
			qo.setPublisher(user.getId());
			qo.setImge(user.getId() +"/" +name + "." + extension);
			ServiceResultDto serviceResultDto=finettalkService.findadd(qo);		
			if(serviceResultDto.getSuccess()) {
				return "200";
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			resMap.put("code", "200");
			resMap.put("message", "出现异常！");
		}
		return "500";
	}


	//精讲后台发布：列表
	@RequestMapping("/Backstagespeak_release")
	public String Backstagespeakrelease(HttpServletRequest request,HttpServletResponse response,
			FinetTalkQo finetTalkQo,@RequestParam(value = "page", defaultValue = "1")Integer page, Model model) {
		if (finetTalkQo == null) {
			finetTalkQo = new FinetTalkQo();
		}
		User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
		Set<Role> set= user.getRoleList();
		Iterator<Role> iter = set.iterator();
		Role roles=new Role();
		while(iter.hasNext()) {
			roles=iter.next();
			break;
		}
		if("3".equals(roles.getNumber()) ||"2".equals(roles.getNumber())) {
			TeachersQo teachersQo=new  TeachersQo();
			teachersQo.setUserId(user.getId());
			Teacher teacher= teachersService.queryUnique(teachersQo);
			finetTalkQo.setPublisher(teacher.getId());
			finetTalkQo.setSeachfinetTalkid(true);
			Pagination pagination = new Pagination();
			pagination.setPageSize(6);
			pagination.setPageNo(page);
			pagination.setCondition(finetTalkQo);
			pagination = finettalkService.queryPagination(pagination);
			SysProperties sysProperties=SysProperties.getInstance();
			String webPath=sysProperties.get("webPath");
			model.addAttribute("finetTalkQo", finetTalkQo);
			model.addAttribute("webPath",webPath);
			model.addAttribute("pagination", pagination);
			return "/finetTalk/finetTalk_Home.html";

		}else if("1".equals(roles.getNumber())) {
			finetTalkQo.setSeachfinetTalkid(true);
			Pagination pagination = new Pagination();
			pagination.setPageSize(6);
			pagination.setPageNo(page);
			pagination.setCondition(finetTalkQo);
			pagination = finettalkService.queryPagination(pagination);
			SysProperties sysProperties=SysProperties.getInstance();
			String webPath=sysProperties.get("webPath");
			model.addAttribute("finetTalkQo", finetTalkQo);
			model.addAttribute("webPath",webPath);
			model.addAttribute("pagination", pagination);
			return "/finetTalk/finetTalk_Home.html";
		}

		return "500";

	}




	//精讲后台发布：id查看
	@RequestMapping("/backstagespeak_view")
	public String view(HttpServletRequest request,HttpServletResponse response,String finetTalkid ,Model model) {
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			FinetTalkQo finetTalkQo=new FinetTalkQo();
			finetTalkQo.setSeachfinetTalkid(true);
			finetTalkQo.setFinetTalkid(Long.parseLong(finetTalkid));
			FinetTalk finetTalk= finettalkService.queryUnique(finetTalkQo);
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}else{
				if(null!=finetTalk) {
					SysProperties sysProperties=SysProperties.getInstance();
					String webPath=sysProperties.get("webPath");
					model.addAttribute("finetTalk",finetTalk);
					model.addAttribute("webPath",webPath);
					return "/finetTalk/finetTalk_View.html";
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return "500";
	}


	//课程删除
	@ResponseBody
	@RequestMapping("/backstagespeak_delete")
	public String delete(HttpServletRequest request,HttpSession session,HttpServletResponse response,String id) {

		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			if(id==null && id=="") {
				return "500";
			}else{
				FinetTalkQo finetTalkQo=new FinetTalkQo();
				finetTalkQo.setFinetTalkid(Long.parseLong(id));
				finetTalkQo.setSeachfinetTalkid(true);
				FinetTalk ft=finettalkService.queryUnique(finetTalkQo);
				SysProperties sysProperties=SysProperties.getInstance();
				String imgPath=sysProperties.get("toragesPath");
				File dest = new File(imgPath+ft.getImge());
				// 路径为文件且不为空则进行删除  
				if (dest.isFile() && dest.exists()) {  
					dest.delete();  
				}
				finettalkService.deleteById(Long.parseLong(id));
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return "200";

	}


	//去往修改精讲页面
	@RequestMapping(value = "/backstagespeak_modify")
	public String modify(String finetTalkid,Model model){
		FinetTalk finetTalk=finettalkService.get(Long.parseLong(finetTalkid));
		if(null!=finetTalk ) {
			SysProperties sysProperties=SysProperties.getInstance();
			String webPath=sysProperties.get("webPath");
			model.addAttribute("finetTalk",finetTalk);
			model.addAttribute("webPath",webPath);
		}
		return "/finetTalk/finetTalk_modify.html";
	}


	//精讲后台：修改
	@ResponseBody
	@RequestMapping(value= "/backstagespeak_update")
	public String update(HttpServletRequest request, HttpServletResponse response, Model model,String fileName,FinetTalkQo qo) {
		Map<String, Object> resMap=new HashMap<String, Object>();

		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			SysProperties sysProperties1=SysProperties.getInstance();
			String fileTemPath=sysProperties1.get("temporaryFileUploadPath");
			String filePath=sysProperties1.get("fileUploadPath");
			SysProperties sysProperties=SysProperties.getInstance();
			String imgPath=sysProperties.get("toragesPath");
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			if(qo.getFinetTalkid()==null) {
				resMap.put("code", "404");
				resMap.put("message", "没有此账号！");
				return JSONObject.fromObject(resMap).toString();
			}
			FinetTalkQo  finetTalkQo=new FinetTalkQo();
			finetTalkQo.setFinetTalkid(qo.getFinetTalkid());
			FinetTalk finetTalk=finettalkService.queryUnique(finetTalkQo);
			MultipartFile pic = null;
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (isMultipart){ 
				MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
				pic = multipartRequest.getFile("pic");
				if(pic!=null) {
					String imge =imgPath+finetTalk.getImge();
					File dest = new File(imge);
					// 路径为文件且不为空则进行删除  
					if (dest.isFile() && dest.exists()) {  
						dest.delete();  
					}
					if (pic.isEmpty()) {
						resMap.put("code", "500");
						resMap.put("message", "上传图片不可为空");
						return JSONObject.fromObject(resMap).toString();
					}
					int returnTag = -1;

					// 获取图片原始文件名
					String originalFilename = pic.getOriginalFilename();
					System.out.println(originalFilename);
					//文件名使用当前时间
					String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
					// 获取上传图片的扩展名(jpg/png/...)
					String extension = FilenameUtils.getExtension(originalFilename);
					String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
					boolean flag1 = false;
					// 判断文件格式是否合法
					for (String str : regular) {
						if (extension.equalsIgnoreCase(str)) {
							flag1 = true;
						}
					}
					if (!flag1) {
						returnTag = 0;
						resMap.put("code", "500");
						resMap.put("message", "上传图片格式不正确！");
						return JSONObject.fromObject(resMap).toString();
					}
					// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
					String path =imgPath + name + "." + extension;
					//图片上传的绝对路径
					File dir = new File(path);
					if (!dir.exists()) {
						dir.mkdirs();
					}
					// 上传图片
					pic.transferTo(new File(path));
					String delfile=filePath+finetTalk.getImge();
					File delvidel = new File(delfile);
					// 路径为文件且不为空则进行删除  
					if (delvidel.isFile() && delvidel.exists()) {  
						delvidel.delete();  
					}
					qo.setImge(name + "." + extension);
					ServiceResultDto ts= finettalkService.findmodify(qo);
				}
				else {
					ServiceResultDto ts= finettalkService.findmodify(qo);
					if(ts.getSuccess()) {
						return "200";
					}
				}

			}



		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "500";

	}



}
